//
//  BDPostCell.m
//  BadBoy
//
//  Created by wen on 2017/9/1.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDPostCell.h"
#import "BDPostHelper.h"
#import "BDControlImageView.h"

@implementation BDPostProfileView {
    BOOL _trackingTouch;
}
- (instancetype)initWithFrame:(CGRect)frame {
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size.width = kScreenWidth;
        frame.size.height = kBDCellProfileHeight;
    }
    self = [super initWithFrame:frame];
    self.exclusiveTouch = YES;
    
    _avatarView = [UIImageView new];
    _avatarView.size = CGSizeMake(40, 40);
    _avatarView.origin = CGPointMake(kBDCellPadding, kBDCellPadding + 3);
    _avatarView.layer.masksToBounds = YES;
    _avatarView.layer.cornerRadius = _avatarView.width / 2.0;
    _avatarView.contentMode = UIViewContentModeScaleAspectFill;
    [self addSubview:_avatarView];
    
    CALayer *avatarBorder = [CALayer layer];
    avatarBorder.frame = _avatarView.bounds;
    avatarBorder.borderWidth = CGFloatFromPixel(1);
    avatarBorder.borderColor = [UIColor colorWithWhite:0.000 alpha:0.090].CGColor;
    avatarBorder.cornerRadius = _avatarView.height / 2;
    avatarBorder.shouldRasterize = YES;
    avatarBorder.rasterizationScale = kScreenScale;
    [_avatarView.layer addSublayer:avatarBorder];
    
    _avatarBadgeView = [UIImageView new];
    _avatarBadgeView.size = CGSizeMake(14, 14);
    _avatarBadgeView.center = CGPointMake(_avatarView.right - 6, _avatarView.bottom - 6);
    _avatarBadgeView.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:_avatarBadgeView];
    
    _nameLabel = [YYLabel new];
    _nameLabel.size = CGSizeMake(kBDCellNameWidth, 24);
    _nameLabel.left = _avatarView.right + kBDCellNamePaddingLeft;
    _nameLabel.centerY = 27;
    _nameLabel.displaysAsynchronously = YES;
    _nameLabel.ignoreCommonProperties = YES;
    _nameLabel.fadeOnAsynchronouslyDisplay = NO;
    _nameLabel.fadeOnHighlight = NO;
    _nameLabel.lineBreakMode = NSLineBreakByClipping;
    _nameLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    [self addSubview:_nameLabel];
    
    _sourceLabel = [YYLabel new];
    _sourceLabel.frame = _nameLabel.frame;
    _sourceLabel.centerY = 47;
    _sourceLabel.displaysAsynchronously = YES;
    _sourceLabel.ignoreCommonProperties = YES;
    _sourceLabel.fadeOnAsynchronouslyDisplay = NO;
    _sourceLabel.fadeOnHighlight = NO;
    __weak BDPostProfileView *weak_self = self;
    _sourceLabel.highlightTapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
        if ([weak_self.cell.delegate respondsToSelector:@selector(cell:didClickInLabel:textRange:)]) {
            [weak_self.cell.delegate cell:weak_self.cell didClickInLabel:(YYLabel *)containerView textRange:range];
        }
    };
    [self addSubview:_sourceLabel];
    
    return self;
}

- (void)setVerifyType:(BDUserVerifyType)verifyType {
    _verifyType = verifyType;
//    switch (verifyType) {
//        case BDUserVerifyTypeStandard: {
//            _avatarBadgeView.hidden = NO;
//            _avatarBadgeView.image = [BDPostHelper imageNamed:@"avatar_vip"];
//        } break;
//        case BDUserVerifyTypeClub: {
//            _avatarBadgeView.hidden = NO;
//            _avatarBadgeView.image = [BDPostHelper imageNamed:@"avatar_grassroot"];
//        } break;
//        default: {
//            _avatarBadgeView.hidden = YES;
//        } break;
//    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    _trackingTouch = NO;
    UITouch *t = touches.anyObject;
    CGPoint p = [t locationInView:_avatarView];
    if (CGRectContainsPoint(_avatarView.bounds, p)) {
        _trackingTouch = YES;
    }
    p = [t locationInView:_nameLabel];
    if (CGRectContainsPoint(_nameLabel.bounds, p) && _nameLabel.textLayout.textBoundingRect.size.width > p.x) {
        _trackingTouch = YES;
    }
    if (!_trackingTouch) {
        [super touchesBegan:touches withEvent:event];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (!_trackingTouch) {
        [super touchesEnded:touches withEvent:event];
    } else {
        if ([_cell.delegate respondsToSelector:@selector(cell:didClickUser:)]) {
            [_cell.delegate cell:_cell didClickUser:_cell.postView.layout.post.user];
        }
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    if (!_trackingTouch) {
        [super touchesCancelled:touches withEvent:event];
    }
}

@end


@implementation BDPostCardView {
    BOOL _isRetweet;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (frame.size.width == 0 && frame.size.height == 0){
        frame.size.width = kScreenWidth;
        frame.origin.x = kBDCellPadding;
    }
    self = [super initWithFrame:frame];
    self.exclusiveTouch = YES;
    
    _imageView = [UIImageView new];
    _imageView.clipsToBounds = YES;
    _imageView.contentMode = UIViewContentModeScaleAspectFill;
    _badgeImageView = [UIImageView new];
    _badgeImageView.clipsToBounds = YES;
    _badgeImageView.contentMode = UIViewContentModeScaleAspectFit;
    _label = [YYLabel new];
    _label.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    _label.numberOfLines = 3;
    _label.ignoreCommonProperties = YES;
    _label.displaysAsynchronously = YES;
    _label.fadeOnAsynchronouslyDisplay = NO;
    _label.fadeOnHighlight = NO;
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:_imageView];
    [self addSubview:_badgeImageView];
    [self addSubview:_label];
    [self addSubview:_button];
    self.backgroundColor = kBDCellInnerViewColor;
    self.layer.borderWidth = CGFloatFromPixel(1);
    self.layer.borderColor = [UIColor colorWithWhite:0.000 alpha:0.070].CGColor;
    return self;
}

- (void)setWithLayout:(BDPostLayout *)layout isRetweet:(BOOL)isRetweet {
    BDPostModel *currentPost = isRetweet ? layout.post.repost : layout.post;
    BOOL haveShopInfo = currentPost.price != 0 || [currentPost.shop isNotEmpty] || [currentPost.address isNotEmpty] || [currentPost.contact isNotEmpty] || [currentPost.consumption isNotEmpty];
    if (haveShopInfo == NO) return;
    self.height = isRetweet ? layout.retweetCardHeight : layout.cardHeight;
    
    /*
     badge: 25,25 左上角 (42)
     image: 70,70 方形
     100, 70 矩形
     btn:  60,70
     
     lineheight 20
     padding 10
     */
    self.width = kBDCellContentWidth;
    _imageView.frame = CGRectMake(0, 0, 70, 70);
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    //获取app中所有icon名字数组
    NSArray *iconsArr = infoDict[@"CFBundleIcons"][@"CFBundlePrimaryIcon"][@"CFBundleIconFiles"];
    //取最后一个icon的名字
    NSString *iconLastName = [iconsArr lastObject];
    _imageView.image = [UIImage imageNamed:iconLastName];
    _label.hidden = NO;
    _label.frame = isRetweet ? layout.retweetCardTextRect : layout.cardTextRect;
    _label.textLayout = isRetweet ? layout.retweetCardTextLayout : layout.cardTextLayout;
    _label.backgroundColor = [UIColor clearColor];
    
    _isRetweet = isRetweet;
    switch (isRetweet ? layout.retweetCardType : layout.cardType) {
        case BDPostCardTypeNone: {
            
        } break;
        case BDPostCardTypeCharge: {
            _button.hidden = NO;
            _badgeImageView.hidden = YES;
            [_button setImage:[UIImage imageNamed:@"lock"] forState:UIControlStateNormal];
            [_button setImage:[UIImage imageNamed:@"lock_on"] forState:UIControlStateSelected];
            _button.size = CGSizeMake(20, self.height);
            _button.right = self.width;
            _button.top = 0;
            
            _button.selected = [layout.post isPurchase];
            _button.backgroundColor = [layout.post isPurchase] ? [UIColor colorWithHexString:@"#cccccc"] : [UIColor colorWithHexString:@"14cd67"];
        } break;
        case BDPostCardTypeFree: {
            _button.hidden = YES;
            _badgeImageView.hidden = NO;
            _badgeImageView.size = CGSizeMake(50, 34);
            _badgeImageView.right = self.width;
            _badgeImageView.top = 0;
            _badgeImageView.image = [UIImage imageNamed:@"free_icon"];
            
        } break;
        default: {
            
        } break;
    }
    
    self.backgroundColor = isRetweet ? [UIColor whiteColor] : kBDCellInnerViewColor;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.backgroundColor = kBDCellInnerViewHighlightColor;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    self.backgroundColor = _isRetweet ? [UIColor whiteColor] : kBDCellInnerViewColor;
    if ([_cell.delegate respondsToSelector:@selector(cellDidClickCard:)]) {
        [_cell.delegate cellDidClickCard:_cell];
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    self.backgroundColor = _isRetweet ? [UIColor whiteColor] : kBDCellInnerViewColor;
}

@end

@implementation BDPostToolbarView
- (instancetype)initWithFrame:(CGRect)frame {
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size.width = kScreenWidth;
        frame.size.height = kBDCellToolbarHeight;
    }
    self = [super initWithFrame:frame];
    self.exclusiveTouch = YES;
    
    _likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _likeButton.exclusiveTouch = YES;
    _likeButton.size = CGSizeMake(CGFloatPixelRound(self.width / 4.0), self.height);
    [_likeButton setBackgroundImage:[UIImage imageWithColor:kBDCellHighlightColor] forState:UIControlStateHighlighted];
    
    _repostButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _repostButton.exclusiveTouch = YES;
    _repostButton.size = CGSizeMake(CGFloatPixelRound(self.width / 4.0), self.height);
    _repostButton.left = CGFloatPixelRound(self.width / 4.0 * 1.0);
    [_repostButton setBackgroundImage:[UIImage imageWithColor:kBDCellHighlightColor] forState:UIControlStateHighlighted];
    
    _commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _commentButton.exclusiveTouch = YES;
    _commentButton.size = CGSizeMake(CGFloatPixelRound(self.width / 4.0), self.height);
    _commentButton.left = CGFloatPixelRound(self.width / 4.0 * 2.0);
    [_commentButton setBackgroundImage:[UIImage imageWithColor:kBDCellHighlightColor] forState:UIControlStateHighlighted];
    
    _sharedButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _sharedButton.exclusiveTouch = YES;
    _sharedButton.size = CGSizeMake(CGFloatPixelRound(self.width / 4.0), self.height);
    _sharedButton.left = CGFloatPixelRound(self.width / 4.0 * 3.0);
    [_sharedButton setBackgroundImage:[UIImage imageWithColor:kBDCellHighlightColor] forState:UIControlStateHighlighted];
    
    _repostImageView = [[UIImageView alloc] initWithImage:[BDPostHelper imageNamed:@"zhuanfa"]];
    _repostImageView.centerY = self.height / 2;
    [_repostButton addSubview:_repostImageView];
    _commentImageView = [[UIImageView alloc] initWithImage:[BDPostHelper imageNamed:@"pinglun"]];
    _commentImageView.centerY = self.height / 2;
    [_commentButton addSubview:_commentImageView];
    _likeImageView = [[UIImageView alloc] initWithImage:[BDPostHelper imageNamed:@"zan"]];
    _likeImageView.centerY = self.height / 2;
    [_likeButton addSubview:_likeImageView];
    _sharedImageView = [[UIImageView alloc] initWithImage:[BDPostHelper imageNamed:@"fengxiang"]];
    _sharedImageView.centerY = self.height / 2;
    [_sharedButton addSubview:_sharedImageView];
    
    _repostLabel = [YYLabel new];
    _repostLabel.userInteractionEnabled = NO;
    _repostLabel.height = self.height;
    _repostLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    _repostLabel.displaysAsynchronously = YES;
    _repostLabel.ignoreCommonProperties = YES;
    _repostLabel.fadeOnHighlight = NO;
    _repostLabel.fadeOnAsynchronouslyDisplay = NO;
    [_repostButton addSubview:_repostLabel];
    
    _commentLabel = [YYLabel new];
    _commentLabel.userInteractionEnabled = NO;
    _commentLabel.height = self.height;
    _commentLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    _commentLabel.displaysAsynchronously = YES;
    _commentLabel.ignoreCommonProperties = YES;
    _commentLabel.fadeOnHighlight = NO;
    _commentLabel.fadeOnAsynchronouslyDisplay = NO;
    [_commentButton addSubview:_commentLabel];
    
    _likeLabel = [YYLabel new];
    _likeLabel.userInteractionEnabled = NO;
    _likeLabel.height = self.height;
    _likeLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    _likeLabel.displaysAsynchronously = YES;
    _likeLabel.ignoreCommonProperties = YES;
    _likeLabel.fadeOnHighlight = NO;
    _likeLabel.fadeOnAsynchronouslyDisplay = NO;
    [_likeButton addSubview:_likeLabel];
    
    _sharedLabel = [YYLabel new];
    _sharedLabel.userInteractionEnabled = NO;
    _sharedLabel.height = self.height;
    _sharedLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    _sharedLabel.displaysAsynchronously = YES;
    _sharedLabel.ignoreCommonProperties = YES;
    _sharedLabel.fadeOnHighlight = NO;
    _sharedLabel.fadeOnAsynchronouslyDisplay = NO;
    [_sharedButton addSubview:_sharedLabel];
    
    UIColor *dark = [UIColor colorWithWhite:0 alpha:0.2];
    UIColor *clear = [UIColor colorWithWhite:0 alpha:0];
    NSArray *colors = @[(id)clear.CGColor,(id)dark.CGColor, (id)clear.CGColor];
    NSArray *locations = @[@0.2, @0.5, @0.8];
    
    _line1 = [CAGradientLayer layer];
    _line1.colors = colors;
    _line1.locations = locations;
    _line1.startPoint = CGPointMake(0, 0);
    _line1.endPoint = CGPointMake(0, 1);
    _line1.size = CGSizeMake(CGFloatFromPixel(1), self.height);
    _line1.left = _repostButton.right;
    
    _line2 = [CAGradientLayer layer];
    _line2.colors = colors;
    _line2.locations = locations;
    _line2.startPoint = CGPointMake(0, 0);
    _line2.endPoint = CGPointMake(0, 1);
    _line2.size = CGSizeMake(CGFloatFromPixel(1), self.height);
    _line2.left = _commentButton.right;
    
    _line3 = [CAGradientLayer layer];
    _line3.colors = colors;
    _line3.locations = locations;
    _line3.startPoint = CGPointMake(0, 0);
    _line3.endPoint = CGPointMake(0, 1);
    _line3.size = CGSizeMake(CGFloatFromPixel(1), self.height);
    _line3.left = _likeButton.right;
    
    _topLine = [CALayer layer];
    _topLine.size = CGSizeMake(self.width, CGFloatFromPixel(1));
    _topLine.backgroundColor = kBDCellLineColor.CGColor;
    
    _bottomLine = [CALayer layer];
    _bottomLine.size = _topLine.size;
    _bottomLine.bottom = self.height;
    _bottomLine.backgroundColor = UIColorHex(e8e8e8).CGColor;
    
    [self addSubview:_repostButton];
    [self addSubview:_commentButton];
    [self addSubview:_likeButton];
    [self addSubview:_sharedButton];
    [self.layer addSublayer:_line1];
    [self.layer addSublayer:_line2];
    [self.layer addSublayer:_line3];
    [self.layer addSublayer:_topLine];
    [self.layer addSublayer:_bottomLine];
    
    __weak BDPostToolbarView *weak_self = self;
    [_repostButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        BDPostCell *cell = weak_self.cell;
        if ([cell.delegate respondsToSelector:@selector(cellDidClickRepost:)]) {
            [cell.delegate cellDidClickRepost:cell];
        }
    }];
    
    [_commentButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        BDPostCell *cell = weak_self.cell;
        if ([cell.delegate respondsToSelector:@selector(cellDidClickComment:)]) {
            [cell.delegate cellDidClickComment:cell];
        }
    }];
    
    [_likeButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        BDPostCell *cell = weak_self.cell;
        if ([cell.delegate respondsToSelector:@selector(cellDidClickLike:)]) {
            [cell.delegate cellDidClickLike:cell];
        }
    }];
    
    [_sharedButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        BDPostCell *cell = weak_self.cell;
        if ([cell.delegate respondsToSelector:@selector(cellDidClickShared:)]) {
            [cell.delegate cellDidClickShared:cell];
        }
    }];
    return self;
}

- (void)setWithLayout:(BDPostLayout *)layout {
    _repostLabel.width = layout.toolbarRepostTextWidth;
    _commentLabel.width = layout.toolbarCommentTextWidth;
    _likeLabel.width = layout.toolbarLikeTextWidth;
    _sharedLabel.width = layout.toolbarSharedTextWidth;
    
    _repostLabel.textLayout = layout.toolbarRepostTextLayout;
    _commentLabel.textLayout = layout.toolbarCommentTextLayout;
    _likeLabel.textLayout = layout.toolbarLikeTextLayout;
    _sharedLabel.textLayout = layout.toolbarSharedTextLayout;
    
    [self adjustImage:_repostImageView label:_repostLabel inButton:_repostButton];
    [self adjustImage:_commentImageView label:_commentLabel inButton:_commentButton];
    [self adjustImage:_likeImageView label:_likeLabel inButton:_likeButton];
    [self adjustImage:_sharedImageView label:_sharedLabel inButton:_sharedButton];
    
    _likeImageView.image = layout.post.praise ? [self likeImage] : [self unlikeImage];
}

- (UIImage *)likeImage {
    static UIImage *img;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        img = [BDPostHelper imageNamed:@"zan_sel"];
    });
    return img;
}

- (UIImage *)unlikeImage {
    static UIImage *img;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        img = [BDPostHelper imageNamed:@"zan"];
    });
    return img;
}

- (void)adjustImage:(UIImageView *)image label:(YYLabel *)label inButton:(UIButton *)button {
    CGFloat imageWidth = image.bounds.size.width;
    CGFloat labelWidth = label.width;
    CGFloat paddingMid = 5;
    CGFloat paddingSide = (button.width - imageWidth - labelWidth - paddingMid) / 2.0;
    image.centerX = CGFloatPixelRound(paddingSide + imageWidth / 2);
    label.right = CGFloatPixelRound(button.width - paddingSide);
}

- (void)setLiked:(BOOL)liked withAnimation:(BOOL)animation {
    BDPostLayout *layout = _cell.postView.layout;
    if (layout.post.praise == liked) return;
    
    UIImage *image = liked ? [self likeImage] : [self unlikeImage];
    int newCount = layout.post.praiseCount;
    newCount = liked ? newCount + 1 : newCount - 1;
    if (newCount < 0) newCount = 0;
    if (liked && newCount < 1) newCount = 1;
    NSString *newCountDesc = newCount > 0 ? [BDPostHelper shortedNumberDesc:newCount] : ASLocalizedString(@"赞");
    
    UIFont *font = [UIFont systemFontOfSize:kBDCellToolbarFontSize];
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(kScreenWidth, kBDCellToolbarHeight)];
    container.maximumNumberOfRows = 1;
    NSMutableAttributedString *likeText = [[NSMutableAttributedString alloc] initWithString:newCountDesc];
    likeText.font = font;
    likeText.color = liked ? kBDCellToolbarTitleHighlightColor : kBDCellToolbarTitleColor;
    YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:likeText];
    
    layout.post.praise = liked;
    layout.post.praiseCount = newCount;
    layout.toolbarLikeTextLayout = textLayout;
    
    if (!animation) {
        _likeImageView.image = image;
        _likeLabel.width = CGFloatPixelRound(textLayout.textBoundingRect.size.width);
        _likeLabel.textLayout = layout.toolbarLikeTextLayout;
        [self adjustImage:_likeImageView label:_likeLabel inButton:_likeButton];
        return;
    }
    
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
        _likeImageView.layer.transformScale = 1.7;
    } completion:^(BOOL finished) {
        
        _likeImageView.image = image;
        _likeLabel.width = CGFloatPixelRound(textLayout.textBoundingRect.size.width);
        _likeLabel.textLayout = layout.toolbarLikeTextLayout;
        [self adjustImage:_likeImageView label:_likeLabel inButton:_likeButton];
        
        [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
            _likeImageView.layer.transformScale = 0.9;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
                _likeImageView.layer.transformScale = 1;
            } completion:^(BOOL finished) {
            }];
        }];
    }];
}
@end


@implementation BDPostView {
    BOOL _touchRetweetView;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size.width = kScreenWidth;
        frame.size.height = 1;
    }
    self = [super initWithFrame:frame];
    self.backgroundColor = [UIColor clearColor];
    self.exclusiveTouch = YES;
    
    _displayAsync = YES;
    
    _contentView = [UIView new];
    _contentView.width = kScreenWidth;
    _contentView.height = 1;
    _contentView.backgroundColor = [UIColor whiteColor];
    static UIImage *topLineBG, *bottomLineBG;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        topLineBG = [UIImage imageWithSize:CGSizeMake(1, 3) drawBlock:^(CGContextRef context) {
            CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
            CGContextSetShadowWithColor(context, CGSizeMake(0, 0), 0.8, [UIColor colorWithWhite:0 alpha:0.08].CGColor);
            CGContextAddRect(context, CGRectMake(-2, 3, 4, 4));//colorWithWhite:0 alpha:0.08
            CGContextFillPath(context);
        }];
        bottomLineBG = [UIImage imageWithSize:CGSizeMake(1, 3) drawBlock:^(CGContextRef context) {
            CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
            CGContextSetShadowWithColor(context, CGSizeMake(0, 0.4), 2, [UIColor colorWithWhite:0 alpha:0.08].CGColor);
            CGContextAddRect(context, CGRectMake(-2, -2, 4, 2));
            CGContextFillPath(context);
        }];
    });
    UIImageView *topLine = [[UIImageView alloc] initWithImage:topLineBG];
    topLine.width = _contentView.width;
    topLine.bottom = 0;
    topLine.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
    [_contentView addSubview:topLine];
    
    
    UIImageView *bottomLine = [[UIImageView alloc] initWithImage:bottomLineBG];
    bottomLine.width = _contentView.width;
    bottomLine.top = _contentView.height;
    bottomLine.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [_contentView addSubview:bottomLine];
    [self addSubview:_contentView];
    
    _profileView = [BDPostProfileView new];
    [_contentView addSubview:_profileView];
    
    __weak BDPostView *weak_self = self;
    _openButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_openButton setTitle:ASLocalizedString(@"全文")forState:UIControlStateNormal];
    [_openButton setTitle:ASLocalizedString(@"收起")forState:UIControlStateSelected];
    [_openButton setTitleColor:KBDColorBlue forState:UIControlStateNormal];
    _openButton.titleLabel.font = [UIFont systemFontOfSize:14];
    _openButton.size = CGSizeMake([[_openButton titleForState:UIControlStateNormal] widthWithFont:_openButton.titleLabel.font], _openButton.titleLabel.font.pointSize);
    [_openButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        if ([weak_self.cell.delegate respondsToSelector:@selector(cellDidClickOpen:)]) {
            [weak_self.cell.delegate cellDidClickOpen:weak_self.cell];
        }
    }];
    [_openButton setEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
    [_contentView addSubview:_openButton];
    
    _menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _menuButton.size = CGSizeMake(30, 30);
    [_menuButton setImage:[BDPostHelper imageNamed:@"xia_2"] forState:UIControlStateNormal];
//    [_menuButton setImage:[BDPostHelper imageNamed:@"timeline_icon_more_highlighted"] forState:UIControlStateHighlighted];
    _menuButton.centerX = self.width - 20;
    _menuButton.centerY = 18;
    [_menuButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        if ([weak_self.cell.delegate respondsToSelector:@selector(cellDidClickMenu:)]) {
            [weak_self.cell.delegate cellDidClickMenu:weak_self.cell];
        }
    }];
    [_contentView addSubview:_menuButton];
    
    _retweetBackgroundView = [UIView new];
    _retweetBackgroundView.backgroundColor = kBDCellInnerViewColor;
    _retweetBackgroundView.width = kScreenWidth;
    [_contentView addSubview:_retweetBackgroundView];
    
    _textLabel = [YYLabel new];
    _textLabel.clipsToBounds = YES;
    _textLabel.left = kBDCellPadding;
    _textLabel.width = kBDCellContentWidth;
    _textLabel.textVerticalAlignment = YYTextVerticalAlignmentTop;
    _textLabel.displaysAsynchronously = YES;
    _textLabel.ignoreCommonProperties = YES;
    _textLabel.fadeOnAsynchronouslyDisplay = NO;
    _textLabel.fadeOnHighlight = NO;
    _textLabel.highlightTapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
        if ([weak_self.cell.delegate respondsToSelector:@selector(cell:didClickInLabel:textRange:)]) {
            [weak_self.cell.delegate cell:weak_self.cell didClickInLabel:(YYLabel *)containerView textRange:range];
        }
    };
    [_contentView addSubview:_textLabel];
    
    _retweetTextLabel = [YYLabel new];
    _retweetTextLabel.left = kBDCellPadding;
    _retweetTextLabel.width = kBDCellContentWidth;
    _retweetTextLabel.textVerticalAlignment = YYTextVerticalAlignmentTop;
    _retweetTextLabel.displaysAsynchronously = YES;
    _retweetTextLabel.ignoreCommonProperties = YES;
    _retweetTextLabel.fadeOnAsynchronouslyDisplay = NO;
    _retweetTextLabel.fadeOnHighlight = NO;
    _retweetTextLabel.highlightTapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
        if ([weak_self.cell.delegate respondsToSelector:@selector(cell:didClickInLabel:textRange:)]) {
            [weak_self.cell.delegate cell:weak_self.cell didClickInLabel:(YYLabel *)containerView textRange:range];
        }
    };
    [_contentView addSubview:_retweetTextLabel];
    
    NSMutableArray *picViews = [NSMutableArray new];
    for (int i = 0; i < 9; i++) {
        BDControlImageView *imageView = [BDControlImageView new];
        imageView.size = CGSizeMake(100, 100);
        imageView.hidden = YES;
        imageView.clipsToBounds = YES;
        imageView.backgroundColor = kBDCellHighlightColor;
        imageView.exclusiveTouch = YES;
        imageView.touchBlock = ^(BDControlImageView *view, YYGestureRecognizerState state, NSSet *touches, UIEvent *event) {
            if (![weak_self.cell.delegate respondsToSelector:@selector(cell:didClickImageAtIndex:)]) return;
            if (state == YYGestureRecognizerStateEnded) {
                UITouch *touch = touches.anyObject;
                CGPoint p = [touch locationInView:view];
                if (CGRectContainsPoint(view.bounds, p)) {
                    [weak_self.cell.delegate cell:weak_self.cell didClickImageAtIndex:i];
                }
            }
        };
        
        UIView *badge = [UIImageView new];
        badge.userInteractionEnabled = NO;
        badge.contentMode = UIViewContentModeScaleAspectFit;
        badge.size = CGSizeMake(56 / 2, 36 / 2);
        badge.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
        badge.right = imageView.width;
        badge.bottom = imageView.height;
        badge.hidden = YES;
        [imageView addSubview:badge];
        
        [picViews addObject:imageView];
        [_contentView addSubview:imageView];
    }
    _picViews = picViews;
    
    _cardView = [BDPostCardView new];
    _cardView.hidden = YES;
    [_contentView addSubview:_cardView];
    
    _toolbarView = [BDPostToolbarView new];
    [_contentView addSubview:_toolbarView];
    
    return self;
}

- (void)setDisplayAsync:(BOOL)displayAsync{
    _displayAsync = displayAsync;
    _profileView.nameLabel.displaysAsynchronously = displayAsync;
    _profileView.sourceLabel.displaysAsynchronously = displayAsync;
    
    _toolbarView.repostLabel.displaysAsynchronously = displayAsync;
    _toolbarView.likeLabel.displaysAsynchronously = displayAsync;
    _toolbarView.commentLabel.displaysAsynchronously = displayAsync;
    _toolbarView.sharedLabel.displaysAsynchronously = displayAsync;
    
    _cardView.label.displaysAsynchronously = displayAsync;
    _textLabel.displaysAsynchronously = displayAsync;
}

- (void)setLayout:(BDPostLayout *)layout needCoverText:(BOOL)needCover{
    _layout = layout;
    
    self.height = layout.isDetail ? layout.detailHeight : layout.height;
    _contentView.top = layout.marginTop;
    _contentView.height = self.height - layout.marginTop - layout.marginBottom;
    
    CGFloat top = 0;
    
    /// 圆角头像


    [_profileView.avatarView setImageWithURL:[NSURL URLWithString:layout.post.user.cover] //profileImageURL
                                 placeholder:[UIImage imageNamed:@"avatar"]
                                     options:YYWebImageOptionIgnorePlaceHolder
                                     manager:[BDPostHelper avatarImageManager] // < 圆角头像manager，内置圆角处理
                                    progress:nil
                                   transform:nil
                                  completion:nil];


    
    if (needCover == YES) {
        _profileView.nameLabel.textLayout = layout.nameTextLayout;
        _profileView.sourceLabel.textLayout = layout.sourceTextLayout;
        _textLabel.textLayout = layout.textLayout;
    }
    
//    _profileView.verifyType = layout.post.user.userVerifyType;
    _profileView.height = layout.profileHeight;
    _profileView.top = top;
    top += layout.profileHeight;
    
    _textLabel.top = top;
    
    if (_layout.isDetail == YES) {
        _textLabel.height = layout.textHeight;
    }else{
        _textLabel.height = layout.isOpen ? layout.textHeight : layout.minTextHeight;
    }

    top += _textLabel.height;
    if (layout.needOpenButton && _layout.isDetail == NO) {
        _openButton.hidden = NO;
        _openButton.selected = layout.isOpen;
        _openButton.top = layout.isOpen ? top : top + kBDCellPaddingText;
        _openButton.left = _textLabel.left;
        top = _openButton.bottom + kBDCellPadding;
    }else{
        _openButton.hidden = YES;
    }
    
    //图片
    if (layout.picHeight > 0) {
        [self _setImageViewWithTop:top isRetweet:NO];
        top += layout.picHeight + kBDCellPadding;
    }else {
        [self _hideImageViews];
    }
    //卡片  在首页 有高度   在详情页 有高度没购买
    if (layout.cardHeight > 0 && (_layout.isDetail == NO || ([layout.post isPurchase] == NO && _layout.isDetail == YES))) {
        _cardView.top = top;
        _cardView.hidden = NO;
        [_cardView setWithLayout:layout isRetweet:NO];
        top += layout.cardHeight + kBDCellPadding;
    }else {
        _cardView.hidden = YES;
    }
    //转发
    if (layout.retweetHeight > 0) {
        _retweetBackgroundView.top = top;
        _retweetBackgroundView.height = layout.retweetHeight;
        _retweetBackgroundView.hidden = NO;
        
        _retweetTextLabel.top = top;
        _retweetTextLabel.height = layout.retweetTextHeight;
        _retweetTextLabel.textLayout = layout.retweetTextLayout;
        _retweetTextLabel.hidden = NO;
        
        if (layout.retweetPicHeight > 0) {
            [self _setImageViewWithTop:_retweetTextLabel.bottom isRetweet:YES];
        } else {
            [self _hideImageViews];
        }
        if (layout.retweetCardHeight > 0) {
            _cardView.top = _retweetTextLabel.bottom;
            _cardView.hidden = NO;
            [_cardView setWithLayout:layout isRetweet:YES];
        }else{
            _cardView.hidden = YES;
        }
    }else{
        _retweetBackgroundView.hidden = YES;
        _retweetTextLabel.hidden = YES;
    }
    if (_layout.isDetail == NO) {
        _toolbarView.hidden = NO;
        _toolbarView.bottom = _contentView.height;
        [_toolbarView setWithLayout:layout];
    }else{
        _toolbarView.hidden = YES;
    }
}

- (void)_hideImageViews {
    for (UIImageView *imageView in _picViews) {
        imageView.hidden = YES;
    }
}

- (void)_setImageViewWithTop:(CGFloat)imageTop isRetweet:(BOOL)isRetweet {
    CGSize picSize = isRetweet ? _layout.retweetPicSize : _layout.picSize;
    NSArray *pics = isRetweet ? _layout.post.repost.images : _layout.post.images;
    int picsCount = (int)pics.count;
    
    for (int i = 0; i < 9; i++) {
        UIView *imageView = _picViews[i];
//        imageView.contentMode = UIViewContentModeScaleAspectFit;
        if (i >= picsCount) {
            [imageView.layer cancelCurrentImageRequest];
            imageView.hidden = YES;
        } else {
            CGPoint origin = {0};
            switch (picsCount) {
                case 1: {
                    origin.x = kBDCellPadding;
                    origin.y = imageTop;
                } break;
                case 4: {
                    origin.x = kBDCellPadding + (i % 2) * (picSize.width + kBDCellPaddingPic);
                    origin.y = imageTop + (int)(i / 2) * (picSize.height + kBDCellPaddingPic);
                } break;
                default: {
                    origin.x = kBDCellPadding + (i % 3) * (picSize.width + kBDCellPaddingPic);
                    origin.y = imageTop + (int)(i / 3) * (picSize.height + kBDCellPaddingPic);
                } break;
            }
            imageView.frame = (CGRect){.origin = origin, .size = picSize};
            imageView.hidden = NO;
            [imageView.layer removeAnimationForKey:@"contents"];
            
            @weakify(imageView);
            [imageView.layer setImageWithURL:[NSURL URLWithString:pics[i]]
                                 placeholder:nil
                                     options:YYWebImageOptionAvoidSetImage
                                  completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
                                      @strongify(imageView);
                                      if (!imageView) return;
                                      if (image && stage == YYWebImageStageFinished) {
                                          int width = image.size.width;
                                          int height = image.size.height;
                                          CGFloat scale = (height / width) / (imageView.height / imageView.width);
                                          if (scale < 0.99 || isnan(scale)) {
                                              if (picsCount == 1) {
                                                  imageView.width =  width / 1.0 / height * imageView.height;
                                              }else{
                                                  // 宽图把左右两边裁掉
                                                  imageView.contentMode = UIViewContentModeScaleAspectFill;
                                                  imageView.layer.contentsRect = CGRectMake(0, 0, 1, 1);
                                              }
                                          } else {
                                              if (picsCount == 1) {
                                                  imageView.width =  width / 1.0 / height * imageView.height;
                                                  imageView.contentMode = UIViewContentModeScaleAspectFit;
                                              }else{// 高图只保留顶部
                                                  imageView.contentMode = UIViewContentModeScaleToFill;
                                                  imageView.layer.contentsRect = CGRectMake(0, 0, 1, (float)width / height);
                                              }
                                          }
                                          ((BDControlImageView *)imageView).image = image;
                                          if (from != YYWebImageFromMemoryCacheFast) {
                                              CATransition *transition = [CATransition animation];
                                              transition.duration = 0.15;
                                              transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
                                              transition.type = kCATransitionFade;
                                              [imageView.layer addAnimation:transition forKey:@"contents"];
                                          }
                                      }
                                  }];
        }
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = touches.anyObject;
    CGPoint p = [touch locationInView:_retweetBackgroundView];
    BOOL insideRetweet = CGRectContainsPoint(_retweetBackgroundView.bounds, p);
    
    if (!_retweetBackgroundView.hidden && insideRetweet) {
        [(_retweetBackgroundView) performSelector:@selector(setBackgroundColor:) withObject:kBDCellHighlightColor afterDelay:0.15];
        _touchRetweetView = YES;
    } else {
        [(_contentView) performSelector:@selector(setBackgroundColor:) withObject:kBDCellHighlightColor afterDelay:0.15];
        _touchRetweetView = NO;
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self touchesRestoreBackgroundColor];
    if (_touchRetweetView) {
        if ([_cell.delegate respondsToSelector:@selector(cellDidClickRetweet:)]) {
            [_cell.delegate cellDidClickRetweet:_cell];
        }
    } else {
        if ([_cell.delegate respondsToSelector:@selector(cellDidClick:)]) {
            [_cell.delegate cellDidClick:_cell];
        }
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [self touchesRestoreBackgroundColor];
}

- (void)touchesRestoreBackgroundColor {
    [NSObject cancelPreviousPerformRequestsWithTarget:_retweetBackgroundView selector:@selector(setBackgroundColor:) object:kBDCellHighlightColor];
    [NSObject cancelPreviousPerformRequestsWithTarget:_contentView selector:@selector(setBackgroundColor:) object:kBDCellHighlightColor];
    
    _contentView.backgroundColor = [UIColor whiteColor];
    _retweetBackgroundView.backgroundColor = kBDCellInnerViewColor;
}

@end


@implementation BDPostCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    _postView = [BDPostView new];
    _postView.cell = self;
    _postView.profileView.cell = self;
    _postView.cardView.cell = self;
    _postView.toolbarView.cell = self;
    [self.contentView addSubview:_postView];
    self.backgroundColor = kBDCellBackgroundColor;
    return self;
}

- (void)prepareForReuse {
    // ignore
}

- (void)setLayout:(BDPostLayout *)layout needCoverText:(BOOL)needCover{
    self.height = layout.height;
    self.contentView.height = layout.height;
    [_postView setLayout:layout needCoverText:needCover];
}


@end
